<template>
    <div id="add-edit-jha">
        <el-dialog :title="titleCon" v-model="isUseDialog" draggable :close-on-click-modal="false" width="60%"
            :before-close="handleClose" :destroy-on-close="true" @close="clean">
            <el-form :model="ruleForm" ref="ruleFormRef" size="default" label-width="120px" :rules="rules">
                <el-row :gutter="2">
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="风险分区">
                            <el-select v-model="riskAreaId" filterable class="m-2" placeholder="选择风险分区"  @change="riskAreaChange">
                                <el-option v-for="item in riskAreaList" :key="item.id" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" v-if="riskAreaId">
                        <el-form-item label="风险分析单元" prop="l_AnalysisUnitId">
                            <el-select v-model="ruleForm.l_AnalysisUnitId" filterable class="m-2" placeholder="选择分析单元"
                                value-key="id" popper-class="set-select" :popper-append-to-body="false">
                                <el-option v-for="item in unitOptions" :key="item.id" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="风险点名称" prop="v_RiskPoint">
                            <el-input v-model="ruleForm.v_RiskPoint" placeholder="风险点名称" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="检查内容" prop="v_CheckContent">
                            <el-input type="textarea" autosize v-model="ruleForm.v_CheckContent" placeholder="检查内容"
                                clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="标准要求">
                            <el-input type="textarea" autosize v-model="ruleForm.v_Standard" placeholder="标准要求"
                                clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="现有控制措施">
                            <el-input type="textarea" autosize v-model="ruleForm.v_ControlMeasure" placeholder="标准要求"
                                clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="风险评价-L">
                            <el-input type="number" min="0" v-model="ruleForm.n_RiskAssessmentL" placeholder="风险评价-L"
                                clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="风险评价-S">
                            <el-input type="number" min="0" v-model="ruleForm.n_RiskAssessmentS" placeholder="风险评价-S"
                                clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="风险评价-R">
                            <el-input type="number" min="0" v-model="ruleForm.n_RiskAssessmentR" placeholder="风险评价-R"
                                clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="风险程度" prop="n_RiskLevel">
                            <el-select filterable v-model="ruleForm.n_RiskLevel" class="m-2" placeholder="选择风险程度"
                                popper-class="set-select" :popper-append-to-body="false">
                                <el-option v-for="item in levelOptions" :key="item.id" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="纠正措施">
                            <el-input type="textarea" autosize v-model="ruleForm.v_CorrectiveMeasure" placeholder="纠正措施"
                                clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
                        <el-form-item label-width="200px" label="产生偏差导致的主要事故类型">
                            <el-input type="textarea" autosize v-model="ruleForm.v_AccidentType"
                                placeholder="产生偏差导致的主要事故类型" clearable />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <el-button @click="cancelUseClick">取消</el-button>
                <el-button type="primary" :disabled="repeatDis" :loading="repeatDis"
                    @click="submitForm(ruleFormRef)">提交</el-button>
            </template>
        </el-dialog>
    </div>
</template>
<script lang="ts">
import { defineComponent, ref, reactive, computed, toRef, toRefs, toRaw, onMounted, watch } from 'vue';
import { FormInstance, FormRules, ElMessage, ElButton, ElCol, ElDatePicker, ElDialog, ElDivider, ElForm, ElFormItem, ElInput, ElOption, ElRadio, ElRow, ElSelect, ElTable, ElTableColumn } from 'element-plus';
import {
    SMSDCLSAdd,
    SMSDCLSUpdate,
    SMSDCRiskPartitionList, SMSDCAnalysisUnitList
} from '/@/api/centerControl/sms';
import { any } from 'video.js/dist/types/utils/events';
/*** 定义接口基础数据类型 */
interface formType {
    repeatDis: Boolean,
    ruleForm: ruleFormType,
}
/*** form 表单数据类型 */
type ruleFormType = {
    l_AnalysisUnitId: any, // 区域/工艺过程(风险管控分析单元Id)
    v_RiskPoint: String, // 风险点名称
    v_CheckContent: String, // 检查内容
    v_Standard: String, // 标准要求
    v_AccidentType: String, // 产生偏差导致的主要事故类型
    v_ControlMeasure: String, // 现有控制措施
    n_RiskAssessmentL: Number | any, // 风险评价-L
    n_RiskAssessmentS: Number | any, // 风险评价-S
    n_RiskAssessmentR: Number | any, // 风险评价-R
    n_RiskLevel: Number | any, // 风险程度
    v_CorrectiveMeasure: String, // 纠正措施
}
export default defineComponent({
    name: 'add-edit-jha',
    components: {},
    props: {
        isUseDialog: {
            type: Boolean,
            default: false,
        },
        repairInfo: {
            type: String,
            default: ''
        },
        commonInfo: {
            type: Array,
            default: () => [],
        },
    },
    setup(props, ctx) {
        const titleCon = ref();
        const ruleFormRef = ref();
        const unitOptions = ref();

        const riskAreaId = ref()
        const riskAreaList = ref([])

        /*** state 引用接口定义基础数据初始值 */
        const state = reactive<formType>({
            repeatDis: false,
            ruleForm: {} as ruleFormType
        })

        /*** 基础验证 rules */
        const rules = reactive<FormRules>({
            /*** 放置验证 */
            n_RiskLevel: [
                { required: true, message: '请选择风险程度', trigger: 'blur' },
            ],
            // 区域/工艺过程(风险管控分析单元Id)
            l_AnalysisUnitId: [
                { required: true, message: '请选择分析单元', trigger: 'change' },
            ],
            // 风险点名称
            v_RiskPoint: [
                { required: true, message: '请输入风险点名称', trigger: 'blur' },
            ],
            // 检查内容
            v_CheckContent: [
                { required: true, message: '请输入检查内容', trigger: 'blur' },
            ],
        })

        /*** handleClose 关闭按钮点击事件 */
        const handleClose = () => {
            cancelUseClick();
        }

        /*** cancelUseClick 取消事件 */
        const cancelUseClick = () => {
            riskAreaId.value = ''
            ctx.emit('cancelUseClick')
        }

        /*** submitForm 提交事件 */
        const submitForm = (formEl: FormInstance | undefined) => {
            if(!riskAreaId.value) return ElMessage.error('请选择风险分区')
            if (!formEl) return
            formEl.validate(async (valid) => {
                if (valid) {
                    state.repeatDis = true;
                    let param = toRaw(state.ruleForm);
                    try {
                        let res: any;
                        if (props.repairInfo !== '') {
                            res = await SMSDCLSUpdate(param);
                        } else {
                            res = await SMSDCLSAdd(param);
                        }
                        if (res.success) {
                            state.repeatDis = false;
                            ctx.emit('controlUseClick');
                            ctx.emit('updateData');
                        } else {
                            state.repeatDis = false;
                            ctx.emit('controlUseClick');
                        }
                    } catch (error) { state.repeatDis = false; }
                } else {
                    console.log('error submit!')
                    return false
                }
            })
        }

        /*** clean 清空数据 */
        const clean = () => {
            ruleFormRef.value.resetFields()
        }

        const riskAreaChange = async (id: number) => {
            unitOptions.value = []
           state.ruleForm.l_AnalysisUnitId = ''
            const res = await SMSDCAnalysisUnitList({ l_RiskPartitionId: id })
            unitOptions.value = res.data.map((item: any) => {
                return {
                    value: item.id,
                    label: item.v_Name
                }
            })
        }

        /*** 监听isUseDialog的变化 */
        watch(() => props.isUseDialog, (newVal) => {
            if (newVal) {
                state.repeatDis = false;
                // unitOptions.value = props.commonInfo;
                if (props.repairInfo !== '') {
                    titleCon.value = '编辑';
                    state.ruleForm = JSON.parse(props.repairInfo);
                } else {
                    titleCon.value = '新增';
                    state.ruleForm = {
                        l_AnalysisUnitId: '', // 区域/工艺过程(风险管控分析单元Id)
                        v_RiskPoint: '', // 风险点名称
                        v_CheckContent: '', // 检查内容
                        v_Standard: '', // 标准要求
                        v_AccidentType: '', // 产生偏差导致的主要事故类型
                        v_ControlMeasure: '', // 现有控制措施
                        n_RiskAssessmentL: '', // 风险评价-L
                        n_RiskAssessmentS: '', // 风险评价-S
                        n_RiskAssessmentR: '', // 风险评价-R
                        n_RiskLevel: '', // 风险程度
                        v_CorrectiveMeasure: '', // 纠正措施
                    }
                }
            }
        })

        /*** isUseDialog 响应弹窗的关闭  */
        const isUseDialog = computed(() => {
            return props.isUseDialog
        })

        onMounted(async () => {
            riskAreaList.value = []
            const res = await SMSDCRiskPartitionList({})
            riskAreaList.value = res.data.map((item: any) => {
                return {
                    label: item.v_Name,
                    value: item.id,
                }
            })

        })

        return {
            handleClose,
            submitForm,
            cancelUseClick,
            clean,
            ruleFormRef,
            titleCon,
            ...toRefs(state),
            isUseDialog,
            rules,
            unitOptions,
            levelOptions: [
                { id: 0, label: '低风险', value: 0 },
                { id: 1, label: '一般风险', value: 1 },
                { id: 2, label: '较大风险', value: 2 },
                { id: 3, label: '重大风险', value: 3 },
            ],
            riskAreaList, riskAreaId, riskAreaChange
        }
    },
})
</script>
<style scoped lang="scss">
:deep(.el-cascader) {
    width: 100%;
}

:deep(.el-select) {
    width: 100% !important;
}

:deep(.el-input) {
    width: 100%;
}
</style>